<?php

/**
 * Simplifying multilinear polynomials 解决办法
 * @param $string
 * @return string
 */

function a($string){
    $preg='/([\+-])(\d{0,})([a-z]+)/';
    if(!in_array($string[0],['+','-'])){
        $string='+'.$string;

    }
    preg_match_all($preg,$string,$groups,PREG_SET_ORDER);
    $tmp=[];
    foreach ($groups as $group){
        $key=str_split($group[3]);
        sort($key);
        $key=implode('',$key);
        $number=intval($group[1].(is_numeric($group[2])?$group[2]:1));
        isset($tmp[$key])?$tmp[$key]+=$number:$tmp[$key]=$number;
    }
    $tmp=array_filter($tmp);
    $string='';

    uksort($tmp,function($a,$b){
        if(strlen($a)<strlen($b)){
            return -1;
        }
        elseif(strlen($a)>strlen($b)){
            return 1;
        }
        return strcmp($a,$b);
    });
    foreach ($tmp as $key=>$n){
        if($n>0){
            $string.="+";
        }
        if($n==1){
            $string.="{$key}";
        }elseif($n==-1){
            $string.="-{$key}";
        }
        else{
            $string.="{$n}{$key}";
        }
    }
    return ltrim($string,'+');
}

echo a('-0c');

